<template>
  <basic-container>
    <div class="avue-crud__search">
      <div class="avue-form" style="width: 100%;">
        <form class="el-form">
          <div class="el-row" span="24">
            <div class="avue-group avue-group--header" index="0" active="1">
              <div role="tablist" aria-multiselectable="true" class="el-collapse">
                <div class="el-collapse-item is-active">
                  <div role="tab" aria-expanded="true" aria-controls="el-collapse-content-4400" aria-describedby="el-collapse-content-4400">
                    <div role="button" id="el-collapse-head-4400" tabindex="0" class="el-collapse-item__header is-active"><i class="el-collapse-item__arrow el-icon-arrow-right is-active"></i></div>
                  </div>
                  <div role="tabpanel" aria-labelledby="el-collapse-head-4400" id="el-collapse-content-4400" class="el-collapse-item__wrap">
                    <div class="el-collapse-item__content">
                      <div class="avue-form__group avue-form__group--flex">
                        <div class="el-col el-col-offset-0 el-col-xs-24 avue-form__row el-col-12" style="padding-left: 10px; padding-right: 10px;">
                          <div class="el-form-item el-form-item--feedback el-form-item--mini avue-form__item--">
                            <label for="projectNo" class="el-form-item__label" style="width: 180px;">
                              <el-select size="mini" v-model="productType" placeholder="类型" @change="changeProdType">
                                <el-option v-for="item in prodtypeList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
                                </el-option>
                              </el-select>
                            </label>
                            <div class="el-form-item__content" style="margin-left:180px;">
                              <div class="el-tooltip el-input el-input--mini el-input--suffix avue-input" search="true" minwidth="120" sortable="sortable" span="6" gutter="20" labelwidth="180" aria-describedby="el-tooltip-3815" tabindex="0">
                                <el-select size="mini" filterable v-model="productId" placeholder="产品名称（产品编码）" @change="changeProduct">
                                  <el-option v-for="item in productList" :key="item.value" :label="item.label" :value="item.value">
                                  </el-option>
                                </el-select>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="el-col el-col-offset-0 el-col-xs-24 avue-form__row el-col-12" style="padding-left: 10px; padding-right: 10px;">
                          <div class="el-form-item el-form-item--feedback el-form-item--mini avue-form__item--">
                            <label for="projectNo" class="el-form-item__label" style="width: 180px;">
                              <el-select size="mini" clearable v-model="searchScType" placeholder="特性类别" @change="changeScType">
                                <el-option v-for="item in scTypeList" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                              </el-select>
                            </label>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
    <avue-crud class='featureTable' :option="option" :table-loading="loading" :data="data" ref="crud" v-model="form" :permission="permissionList" @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave" :before-open="beforeOpen" @selection-change="selectionChange" @refresh-change="refreshChange"  @on-load="onLoad">
      <template slot="menuRight">
        <table-right :crud='$refs.crud' :data='data' :searchBtn='false' :columnBtn='true' :addPermission="permission.publiccraft_feature_add&&this.productId" :handleAdd="handleAdd" :handleDelete="handleDelete" :delPermission="permission.publiccraft_feature_delete" :refreshChange='refreshChange'>
          <!-- <el-button type="text" icon="el-icon-download" v-if="permission.publiccraft_feature_export" @click="handleExport">导出</el-button> -->
          <el-button type="text" icon="el-icon-document-copy" v-if="permission.publiccraft_feature_copy" @click="copyScFn">复制</el-button>
        </table-right>
      </template>
      <template slot="notation" slot-scope="{row}">
        <img style="width: auto; height: 25px" :src="row.notation" alt="">
      </template>
      <template slot-scope="{row}" slot='standard'>
        <el-image v-if="row.standardType=='2'" style="width: 40px; height: 40px" :src="row.standard" :preview-src-list="[row.standard]">
        </el-image>
        <span v-else>{{row.standard}}</span>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
          <el-button icon="el-icon-view" size="small" type="text" @click.stop="operateFn(row, 'view')" v-if="permission.publiccraft_feature_view"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
          <el-button :disabled="row.status>1" icon="el-icon-edit" size="small" type="text" @click.stop="operateFn(row, 'edit')" v-if="permission.publiccraft_feature_edit"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button :disabled="row.status>1" icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(row)" v-if="permission.publiccraft_feature_delete"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <el-dialog v-dialogdrag :close-on-click-modal='false' top="15vh" :title="title" :visible.sync="showAddDialog" width="80%" append-to-body>
      <featureAdd @reload="reload" type="innerUse" :form="productForm" @close="showAddDialog=false" v-if="showAddDialog" />
    </el-dialog>
    <el-dialog v-dialogdrag :close-on-click-modal='false' top="15vh" :title="title" :visible.sync="showEditDialog" width="80%" append-to-body>
      <featureEdit type="innerUse" @reload="reload" :productId="productId" :openType="openType" :rowInfo="rowInfo" @close="showEditDialog=false" v-if="showEditDialog" />
    </el-dialog>
    <el-dialog v-dialogdrag :close-on-click-modal='false' top="15vh" title="选择复制到哪个产品" :visible.sync="showCopyDialog" width="700px" append-to-body>
      <div style="width: 660px">
        <el-select style="width: 160px" size="mini" v-model="productType" placeholder="类型" disabled>
          <el-option v-for="item in prodtypeList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
          </el-option>
        </el-select>
        <el-select style="width: 360px;" size="mini" filterable v-model="productId1" placeholder="产品名称（产品编码）">
          <el-option v-for="item in productList1" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <div class="center mt">
          <el-button icon="el-icon-circle-plus-outline" :loading="copyLoading" type="primary" size="mini" @click="copyConfirm">保 存</el-button>
          <el-button icon="el-icon-circle-close" :loading="copyLoading" size="mini" @click="showCopyDialog = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getFeatureListNew, removeFeature, prdScCopy } from '@/api/project/productData/processData';
import { getQualityList } from '@/api/project/information/base';
import { masterProducts } from '@/api/project/productData/product';
import { getEquipments } from '@/api/project/productData/equipment';
import { getBusinessList } from '@/api/zidian';
import { mapGetters } from 'vuex';
import { init } from '@/mixins/init';
import { getToken } from '@/util/auth';
import featureAdd from './featureAdd.vue'
import featureEdit from './featureEdit.vue'
export default {
  components: { featureAdd, featureEdit },
  mixins: [init],
  data() {
    return {
      scTypeList: [
        {
          label: '产品特性',
          value: '1'
        },
        {
          label: '过程特性',
          value: '2'
        }
      ],
      searchScType: '',
      title: '',
      openType: '',
      prodtypeList: [],
      productList: [],
      productList1: [],
      showAddDialog: false,
      showEditDialog: false,
      showCopyDialog: false,
      copyLoading: false,
      productForm: {},
      productId: '',
      productId1: '',
      materialName: '',
      materialNo: '',
      innerDrawingNo: '',
      option: {
        page: false,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        addBtn: false,
        menuWidth: 100,
        columnBtn: true,
        filterBtn: true,
        column: [
          {
            label: '特性类别',
            prop: 'scType',
            type: 'select',
            // sortable: true,
            dicData: [
              {
                label: '产品特性',
                value: '1'
              },
              {
                label: '过程特性',
                value: '2'
              }
            ]
          },
          {
            label: '产品特性',
            prop: 'productSc',
            overHidden: true,
          },
          {
            label: '过程特性',
            prop: 'procedureSc',
            overHidden: true,
          },
          {
            label: '特性分类',
            prop: 'scKind',
            type: 'select',
            dicData: [],
            props: {
              label: 'quaType',
              value: 'id',
            },
          },
          {
            label: '特殊特性标识',
            prop: 'notation',
            slot: true,
          },
        ],
      },
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.publiccraft_feature_add, false),
        viewBtn: this.vaildData(this.permission.publiccraft_feature_view, false),
        delBtn: this.vaildData(this.permission.publiccraft_feature_delete, false),
        editBtn: this.vaildData(this.permission.publiccraft_feature_edit, false),
      };
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    copyScFn () {
      if (this.data.length == 0) {
        this.$message.warning('该产品的特性清单为空，无法复制')
        return
      }
      this.productId1 = ''
      this.showCopyDialog = true
    },
    copyConfirm () {
      if (!this.productId1) {
        this.$message.warning('请选择要复制到哪个产品')
        return
      }
      this.copyLoading = true
      prdScCopy(this.productId, this.productId1).then(res => {
        this.$message.success(res.data.msg)
        this.copyLoading = false
        this.showCopyDialog = false
        this.productId = this.productId1
        this.searchChange()
      }).catch(() => {
        this.copyLoading = false
        this.showCopyDialog = false
      })
    },
    handleAdd () {
      this.title = '新增'
      this.isView = false
      this.showAddDialog = true
    },
    operateFn (row,type) {
      if (type == 'view') {
        this.title = '查看'
        this.openType = 'view'
        this.rowInfo = row
        this.showEditDialog = true
      } else {
        this.title = '编辑'
        this.openType = 'edit'
        this.rowInfo = row
        this.showEditDialog = true
      }
    },
    handleExport() {
      this.$confirm('是否导出特性清单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        window.open(
          `/api/blade-user/export-user?${this.website.tokenHeader}=${getToken()}&account=${this.search.account}&realName=${
            this.search.realName
          }`
        );
      });
    },
    changeProdType(value) {
      this.productId = '';
      switch (value) {
        case '1':
          this.getProducts();
          break;
        case '2':
          this.getMoulds();
          break;
      }
    },
    changeProduct(value) {
      if (!value) {
        return;
      }
      this.searchChange();
    },
    changeScType () {
      this.searchChange();
    },
    changeSpecialType() {
      this.searchChange();
    },
    searchChange() {
      this.searchProductId = this.productId;
      this.productList1 = this.productList.filter(item => item.value!=this.productId)
      this.productList.every((item) => {
        if (item.value == this.productId) {
          this.materialName = item.materialName;
          this.innerDrawingNo = item.innerDrawingNo;
          this.materialNo = item.materialNo;
          return false;
        } else {
          return true;
        }
      });
      this.onLoad();
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeFeature(row.id);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let isApproving = this.selectionList.some(item => {
        return item.status > 1
      })
      if (isApproving) {
        this.$message.error('所选数据中包含审批中或已通过的数据，不能删除')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeFeature(this.ids);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    async getProducts() {
      await masterProducts({ productType: 'PC' }).then((res) => {
        if (res.data.data.length == 0) {
          this.$message.error('请先维护产品信息');
          return;
        }
        this.productList = res.data.data.map((item) => {
          return {
            id: item.id,
            label: item.materialName + '(' + item.materialNo + ')',
            value: item.id,
            materialName: item.materialName,
            innerDrawingNo: item.innerDrawingNo,
            materialNo: item.materialNo,
          };
        });
        if (!this.productId) {
          this.productId = res.data.data[0].id;
          this.searchChange();
        }
      });
    },
    getMoulds() {
      getEquipments({ materialFlag: 'EM', quotaFlag: '2' }).then((res) => {
        if (res.data.data.length == 0) {
          this.$message.error('请先维护模具信息');
          return;
        }
        this.productList = res.data.data.map((item) => {
          return {
            id: item.id,
            label: item.materialName + '(' + item.materialNo + ')',
            value: item.id,
            materialName: item.materialName,
            innerDrawingNo: item.innerDrawingNo,
            materialNo: item.materialNo,
          };
        });
        if (!this.productId) {
          this.productId = res.data.data[0].id;
          this.materialName = res.data.data[0].materialName;
          this.searchChange();
        }
      });
    },
    init() {
      getQualityList().then((res) => {
        this.findObject(this.option.column, 'scKind').dicData = res.data.data.map(item => {
          item.quaType = item.quaType + '-' + item.definition
          return item
        })
      });
      getBusinessList('feature_source').then((res) => {
        this.prodtypeList = res.data.data;
        this.productType = this.prodtypeList[0].dictKey;
        masterProducts({ productType: 'PC' }).then((res) => {
          if (res.data.data.length == 0) {
            this.$message.error('请先维护产品信息');
            return;
          }
          this.productList = res.data.data.map((item) => {
            return {
              id: item.id,
              label: item.materialName + '(' + item.materialNo + ')',
              value: item.id,
              materialName: item.materialName,
              innerDrawingNo: item.innerDrawingNo,
              materialNo: item.materialNo,
            };
          });
          if (!this.productId) {
            this.productId = res.data.data[0].id;
            this.materialName = res.data.data[0].materialName;
          }
          this.searchChange();
        });
      });
    },
    reload () {
      this.searchChange();
      this.showAddDialog = false
      this.showEditDialog = false
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (!this.searchProductId) {
        return false;
      }
      this.query.productId = this.searchProductId;
      this.query.specialType = this.specialType ? this.specialType : null;
      this.productForm = {
        materialName: this.materialName,
        materialNo: this.materialNo,
        innerDrawingNo: this.innerDrawingNo,
        productId: this.productId
      }
      if (this.searchScType) {
        this.query.scType = this.searchScType
      } else {
        this.query.scType = undefined
      }
      getFeatureListNew(Object.assign(params, this.query)).then((res) => {
        this.data = res.data.data;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
